<template>
  <div class="headuser">
    <van-nav-bar title="个人信息" left-arrow @click-left="$router.back()">
    </van-nav-bar>
    <input
      type="file"
      hidden
      id="file"
      accept="image/*"
      ref="file"
      @change="change"
    />

    <van-cell title="头像" center>
      <!-- 点击label标签 也会触发 他for的那个元素的点击 -->
      <label for="file">
        <van-image
          width="50"
          height="50"
          round
          fit="cover"
          :src="userInfo.avatar"
        />
      </label>
    </van-cell>
    <van-cell
      title="昵称"
      is-link
      :value="userInfo.nickname"
      :to="{ path: '/nickedit', query: { nickname: userInfo.nickname } }"
    />
    <van-cell
      title="性别"
      is-link
      :value="userInfo.sex || '请选择性别'"
      @click="sexPickerShow = true"
    />

    <van-popup v-model="sexPickerShow" position="bottom">
      <van-picker
        show-toolbar
        title="选择"
        @confirm="sexPickerConfirm"
        @cancel="sexPickerShow = false"
        :columns="sexColumns"
      />
    </van-popup>

    <van-cell
      title="生日"
      is-link
      :value="userInfo.birthday || '请选择生日'"
      @click="dataPickerShow = true"
    />
    <van-popup v-model="dataPickerShow" position="bottom">
      <van-datetime-picker
        :value="
          userInfo.birthday ? new Date(userInfo.birthday) : new Date(2000, 0, 1)
        "
        type="date"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="dataPickerConfirm"
        @cancel="dataPickerShow = false"
      />
    </van-popup>

    <van-button type="primary" size="large" block @click="submit"
      >确定</van-button
    >
  </div>
</template>
<script>
import { mapActions } from "vuex";
import { editUserInfo } from "@/api/user";
import sexPickerMixin from "./sexPickerMixin";
import dataPickerMixin from "./dataPickerMixin";
export default {
  name: "userInfo",
  data() {
    return {
      userInfo: {},
    };
  },
  mixins: [sexPickerMixin, dataPickerMixin],
  mounted() {
    console.log(this.userInfo);
    // let nickname = sessionStorage.getItem("nickname");
    // if (nickname) {
    //   this.userInfo.nickname = nickname;
    // }
  },
  // keep-alive 后 又新增加了两个新的生命周期 钩子

  //激活 当被缓存的组件  再次被打开时 他的加载时机 比较晚 比mounted还要玩 比挂载后还要晚
  activated() {
    let nickname = sessionStorage.getItem("nickname");
    if (nickname) {
      this.userInfo.nickname = nickname;
    }
  },
  //私活 被缓存的组件 加入到缓存时（即将销毁时不会被销毁）
  deactivated() {
    console.log("加入到缓存");
  },

  computed: {
    //1.这样写的问题是  会污染vuex数据
    // userInfo() {
    //   return this.$store.state.userInfo;
    // },
  },
  watch: {
    //数据无污染 刷新后也能拿到
    "$store.state.userInfo": {
      immediate: true, //初始化后立刻进行监听
      handler(n, o) {
        this.userInfo = JSON.parse(JSON.stringify(n));
      },
    },
  },
  created() {
    //数据回填
    // 需要拿到用户数据
    // 其实不用在这拿
    //从vuex拿数据
    //问题是  刷新以后 拿不到
    // this.userInfo = JSON.parse(JSON.stringify(this.$store.state.userInfo)); //深度拷贝了一下vuex里的userInfo
  },

  // mounted: {},
  methods: {
    ...mapActions(["upload"]),

    //性别选择器 确定事件
    async change(e) {
      console.log(e.target.files); //没有使用vant  我们把他封装成vant的
      let file = e.target.files[0]; //二进制

      //1. 前端预览   FileReader    base64
      //2. url.createObjectURL   前端预览图片

      this.userInfo.file = file;
      let fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = (e) => {
        this.userInfo.avatar = e.target.result;
      };
      // let fileList = [
      //   {
      //     file,
      //     //conent
      //   },
      // ]; //和vant上传组件形状一样
      // let res = await this.upload(fileList);
      // console.log(res);
    },

    //submit
    async submit() {
      // console.log(this.userInfo);
      let {
        _id,
        nickname,
        avatar,
        file,
        sex = "",
        birthday = "",
      } = this.userInfo;
      if (file) {
        // 有 证明咱们上传头像
        let fileList = [
          {
            file,
          },
        ]; //和vant上传组件形状一样
        let res = await this.upload(fileList);
        avatar = res[0];
      }
      editUserInfo({
        uid: _id,
        nickname,
        avatar,
        sex,
        birthday,
      }).then((res) => {
        console.log(res);
        //更新成功后 需要返回 更新一下vuex的数据
        // 最快的方案 重新调接口

        //改完数据后 返回 没同步更新
        this.$toast(res.msg);
        if (res.code == 0) {
          //通知服务器 已经改了
          //但是 本地vuex数据还没改

          //1.直接调接口 严谨 但是浪费了一点点
          // this.$store.dispatch("getUserInfo", localStorage.getItem("token"));
          //2.本地修改  覆盖
          this.$store.commit("change", {
            key: "userInfo",
            value: {
              _id,
              nickname,
              avatar,
              sex,
              birthday,
            },
          });

          setTimeout((v) => {
            this.$router.back();
          }, 500);
        }
      });
    },
  },
};
</script>
<style lang="less">
.headuser {
  background-color: @color3;
  height: 100vh;
  // margin-top: 26px;

  .van-button--block {
    width: 85%;
    margin-left: 6.8vw;
    margin-top: 6.93333vw;
    border-radius: 9.33333vw;
  }
}
</style>